// global variables for inverted index and countries dictionary
var index = null;
var countries = null;

/*
 * Loads information about countries
 */
function loadCountriesDict() {
    $.getJSON("/static/data/countries.json", function(jsonData) {
        countries = jsonData;
    });
}

loadCountriesDict();

/*
 * Loads inverted index for searching countries
 */
function loadIndex() {
    $.getJSON("/static/data/countriesIndex.json", function(jsonData) { 
        index = jsonData;
    });
}

loadIndex();

/*
 * Returns id of the country which is the best match for the query
 */
function bestCountryMatch(query) {
    if (!index || !countries) {
        return null;
    }
    // normalization (remove whitespace and convert to lower case)
    query = query.toLowerCase().replace(/\s/g, '');

    if (query.length < 2) {
        return null;
    }

    // first check if it's an ISO of a country
    if (query.length <= 3) {
        var isoQuery = query.slice(0,2).toUpperCase();
        if (isoQuery in countries) {
            return isoQuery;
        }
    }

    //count all matches
    var matches = {};
    for (var i=0; i<query.length-2; i++) {
        var trigram = query.slice(i,i+3);
        var matchCountries = index[trigram];
        if (matchCountries) {
            $.each(matchCountries, function(index, countryId) {
                if (!(countryId in matches)) {
                    // prefer countries with the same first letter
                    if (countries[countryId]['name'][0] == query[0]) {
                        matches[countryId] = 3;
                    } else {
                        matches[countryId] = 1;
                    }
                    // prefer well-known countries
                    // (use population as heuristics)
                    var population =
                        parseInt(countries[countryId]['population']);
                    if (population > 10000000) {
                        matches[countryId] += 1.2;
                    } else {
                        matches[countryId] += population / 10000000;
                    }
                } else {
                    matches[countryId] += 1;
                }
            });
        }
    }

    // find the country with most matches
    var bestCountry = '';
    var bestMatches = 0;
    for (var countryId in matches) {
        if ((matches[countryId] > bestMatches)
            || (matches[countryId] == bestMatches
                && countries[countryId]['name'].length <
                countries[bestCountry]['name'].length)) {
            bestMatches = matches[countryId];
            bestCountry = countryId;
        }
    }
    return bestCountry;
}

